<?php

namespace app\admin\controller;

use app\admin\model\Address;
use app\admin\model\OrderDistribution;
use app\admin\model\Orderitem;
use app\admin\model\ProductBatchStock;
use app\common\DictConstant;
use app\common\model\ExpressTrace;
use think\Db;
use think\Exception;
use think\Request;

//线上销售
class Saleol extends Base
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'order';
        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
        $status = get_order_status();
        $method = get_deliver_method();
        $this->assign('status',$status);
        $this->assign('method',$method);
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        $model = model($this->model);
        if ($request->isAjax()){
            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            // 排序条件
            $order = 'a.create_date DESC';
            $where = $this->getFilterWhere($request);
            if(!isset($where['status'])){
                $wheres = 'status !=5 AND status !=10';
            }else{
                $wheres = true;
            }
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            $fields = 'a.id,a.order_no,a.total,a.pay_method,a.deliver_method,a.my_collect_id,a.create_date,a.discount_price,a.freight,a.status,m.account_number';
            $data = $model->alias('a')
                ->join('member m','a.member_id = m.id')
                ->where($where)
                ->where($wheres)
                ->field($fields)
                ->limit($start,$length)
                ->order($order)
                ->select();

            if (!$data){
                return $this->error('未查询到数据');
            }

            $count = $model->alias('a')
                ->join('member m','a.member_id = m.id')
                ->where($where)
                ->where($wheres)
                ->field($fields)
                ->count();

            foreach($data as $v)
            {
                //支付方式
                $v['show_deliver_method'] = show_deliver_method($v['deliver_method']);
                //优惠券
                if (empty($v['my_collect_id'])){
                    $v['my_collect_id'] = '-';
                }else{
                    $couponMdl = model('Membercoupon');
                    $coupon = $couponMdl
                        ->alias('a')
                        ->join('coupon c','a.coupon_id = c.id')
                        ->where(['a.id'=>$v['my_collect_id']])
                        ->field('c.name')
                        ->find();
                    $v['my_collect_id'] = $coupon['name'];
                }
                /*
                 *订单查询购买商品 查询赠送积分
                 * */
                //获取积分

                //获取金额
                $v['pay_type'] = show_pay_type($v['pay_method']);
                $v['total'] = $v['total'] /100;
                $v['freight'] = $v['freight'] /100;
                $v['discount_price'] = $v['discount_price'] /100;
                $v['pay_reality'] = $v['total'] + $v['discount_price'];
            }
                $result = [
                    'code' => '0',
                    'msg' => '请求成功',
                    'data' => $data,
                    'count' => $count,
                ];

                return json($result);
        }
        return self::show($this->indexView, [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /*
     * Detail
     * */
    public function detail()
    {
        $param = $this->request->param();
        $model = model($this->model);
        $id = $param['id'];
        $info = $model
            ->where('id',$id)
            ->find();
        //金额
        //dump($info);exit;
        if(!empty($info->address_id)){
            //快递
            $Address = Address::where('id',$info->address_id)->find();
            if($Address){
                $info['member'] = $Address['name'] .'　'. $Address['phone'];
                $info['address'] = $Address['province'] . $Address['city'] . $Address['area'] .$Address['details'];
            }else{
                $info['member'] = '';
                $info['address'] = '';
            }
            //运费
            $info['freight'] = sprintf("%.2f",$info['freight'] /100);
            if($info->status == '备货完成'){
                $express = db('express')->where('status',1)->field('name,code')->select();
                $this->assign('express',$express);
            }
        }else{
            //自提

            $Pickuppoint = \app\admin\model\Pickuppoint::where('id',$info->pickuppoint_id)->find();
            if($Pickuppoint){
                $info['pickuppoint_name'] = $Pickuppoint->name;
                $info['pickuppoint_address'] = $Pickuppoint->region . $Pickuppoint->address;
                $info['busstime'] = $Pickuppoint->business_start_time . '-' . $Pickuppoint->business_end_time;
            }else{
                $info['pickuppoint_name'] = '';
                $info['pickuppoint_address'] = '';
                $info['busstime'] = '';
            }
        }
        $info['order_price'] = sprintf("%.2f",$info['order_price'] /100);
        $info['discount_price'] = sprintf("%.2f",($info['discount_price'] + $info['first_order_reduce']) /100);
        $info['total'] = sprintf("%.2f",$info['total'] /100);
        //付款方式
        $info['pay_method'] = show_pay_type($info['pay_method']);

        //收货信息
        $this->assign('info',$info);


        // Reset filter
        if ($this->request->param('reset')) {
            return redirect(fullUrl($this->request->path()));
        }
        if($this->request->isAjax()){
            $orderMdl = model('Orderitem');
            $fields = 'a.*,p.bar_code,p.member_integral';
            $order = $orderMdl->alias('a')
                ->join('product p','p.id=a.product_id')
                ->where('a.order_id',$id)
                ->where('a.after_sale_status','in',[0,1,3,5])
                ->field($fields)
                ->select();
            foreach($order as $k => $v){
                $v['key'] = $k + 1;
                $v['member_integral'] = $v['member_integral'] * $v['count'];
                $v['total_price'] = sprintf("%.2f",$v['price']*$v['count']/100);
                $res = OrderDistribution::where(['order_id'=>$v['order_id'],'product_id'=>$v['product_id']])->select();
                $info = '';
                foreach ($res as $value){
                    $info .= '（生产日期【'.$value['production_time'] . '】发货数量为：' . $value['num'] . '）';
                }
                $v['beihuo_info'] = $info;
            }
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $order
            ];

            return json($result);
        }


        return self::show('detail', [
            'pageSize' => ['url' => fullUrl($this->request->path())],
            'searchFields' => $this->searchFields,
            'param' => $this->request->param()
        ]);
    }

    public function search_cangku(Request $request){
        $param = $request->param();
        $this->assign('product_id',$param['productid']);
        $this->assign('order_id',$param['order_id']);
        return $this->fetch();
    }

    //获取供应商下的商品
    public function get_cangkuproduct(Request $request){
        $param = $request->param();
        if(empty($param['product_id'])){
            return $this->error('缺少参数');
        }
        $info = ProductBatchStock::where('product_id',$param['product_id'])->select();
        $order_distribution = db('order_distribution')->where(['order_id'=>$param['order_id'],'product_id'=>$param['product_id']])->select();

        if($order_distribution){
            foreach ($info as &$value){
                foreach ($order_distribution as $v){
                    if($v['product_id'] == $value['product_id'] && $v['production_time'] == $value['production_time']){
                        $value['se_num'] = $v['num'];
                        $value['LAY_CHECKED'] = true;
                        break;
                    }
                }
            }

        }
        $count = count($info);
        $result = [
            'code' => '0',
            'msg' => '',
            'data' => $info,
            'count' => $count,
        ];

        return json($result);
    }

    public function edit_fahuonum(Request $request){
        $param = $request->param();
        $order_id = $param['order_id'];
        $product_id = $param['product_id'];
        $production_time = $param['production_time'];
        $updatenum = $param['value'];
        $Orderitem = Orderitem::where(['order_id'=>$order_id,'product_id'=>$product_id])->field('count')->find();
        $order_pro_num = $Orderitem['count'];
        $OrderDistribution = OrderDistribution::where(['order_id'=>$order_id,'product_id'=>$product_id])->where('production_time','<>',$production_time)->select();
        $othernum = 0;
        foreach ($OrderDistribution as $v){
            $othernum += $v['num'];
        }

        $updateallnum = $othernum + $updatenum;

        if($updateallnum > $order_pro_num){
            return $this->error('发货数量不能大于用户购买数量');
        }
        return $this->success('操作成功');


    }

    /**
     * 修改商品对应批次的备货数量
     * @param Request $request
     */
    public function save_beihuo_session(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['order_id'])){
                return $this->error('参数异常');
            }
            $Order = \app\common\model\Order::where('id',$param['order_id'])->find();
            if($Order){
                if($Order->status != 2){
                    return $this->error('订单状态异常');
                }
            }else{
                return $this->error('订单不存在');
            }
            if(!isset($param['temp'])){
                return $this->error('请选择并填写发货数量');
            }
            $paramdata = $param['temp'];
            if(is_array($paramdata)){
                $data = [];
                $product_id = $paramdata[0]['product_id'];
                $updatenum = 0;
                foreach ($paramdata as $v){
                    array_push($data,[
                        'product_batch_stock_id'=>$v['product_batch_stock_id'],
                        'order_id' => $param['order_id'],
                        'product_id' => $v['product_id'],
                        'production_time' => $v['production_time'],
                        'num' => $v['se_num']
                    ]);
                    $updatenum += $v['se_num'];
                }
                $Orderitem = Orderitem::where(['order_id'=>$param['order_id'],'product_id'=>$product_id])->field('count,after_sale_status')->find();
                if(!in_array($Orderitem['after_sale_status'],[0,3,5])){
                    return $this->error('该商品在售后，不能备货');
                }

                if($updatenum!=$Orderitem['count']){
                    return $this->error('发货数量必须等于用户购买数量');
                }
                $pros = db('order_distribution')->where(['order_id'=>$param['order_id'],'product_id'=>$product_id])->select();
                if($pros){
                    $delearr = [];
                    foreach ($pros as $v){
                        $falg = false;
                        foreach ($paramdata as $val){
                            if($val['production_time'] == $v['production_time']){
                                $falg = true;
                            }
                        }
                        if(!$falg){
                            //要删除的
                            array_push($delearr,$v);
                        }
                    }
                    if($delearr){
                        $deleidarr = [];
                        foreach ($delearr as $v){
                            array_push($deleidarr,$v['id']);
                        }
                        Db::table('order_distribution')->delete($deleidarr);
                    }
                }

                $updatearr = [];
                $insertarr = [];
                foreach ($data as $v){
                    $res = OrderDistribution::where(['order_id'=>$v['order_id'],'product_id'=>$v['product_id'],'production_time'=>$v['production_time']])->find();
                    if($res){
                        //更新
                        array_push($updatearr,[
                            'id' => $res['id'],
                            'num' => $v['num']
                        ]);
                    }else{
                        //添加
                        array_push($insertarr,[
                            'product_batch_stock_id'=>$v['product_batch_stock_id'],
                            'order_id' => $param['order_id'],
                            'product_id' => $v['product_id'],
                            'production_time' => $v['production_time'],
                            'num' => $v['num']
                        ]);
                    }
                }
                try{
                    $model = new OrderDistribution();
                    if($updatearr){
                        $model->saveAll($updatearr);
                    }
                    if($insertarr){
                        $model->saveAll($insertarr);
                    }
                    return $this->success('操作成功');
                }catch (Exception $ex){
                    return $this->success('操作失败');
                }
            }else{
                return $this->error('参数异常');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    /**
     * 确认备货
     * @param Request $request
     */
    public function confirm_beihuo(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['order_id'])){
                return $this->error('参数非法');
            }
            Db::startTrans();
            try{
                $Order = \app\common\model\Order::where('id',$param['order_id'])->field('id,status,address_id')->find();
                if($Order){
                    if($Order->status == DictConstant::OrderPendingDelivery){
                        $Orderitem = Orderitem::where('order_id',$Order['id'])->field('after_sale_status')->select();
                        $flag = true;
                        foreach ($Orderitem as $v){
                            if($v['after_sale_status'] == 1){
                                $flag = false;
                                break;
                            }
                        }
                        if(!$flag){
                            return $this->error('有商品正在售后，不能备货');
                        }
                        if($Order->address_id){
                            $updatestatus = DictConstant::Order_Stock_up;
                        }else{
                            $updatestatus = DictConstant::Order_Nodelivery;
                        }
                        $Order->status = $updatestatus;
                        $Order->save();
                        Orderitem::where('order_id',$param['order_id'])->update(['old_status'=>$updatestatus]);
                        //更新批次库存
                        $OrderDistribution = OrderDistribution::where('order_id',$param['order_id'])->select();
                        foreach ($OrderDistribution as $v){
                            ProductBatchStock::where(['product_id'=>$v['product_id'],'production_time'=>$v['production_time']])->setDec('num',$v['num']);
                            ProductBatchStock::where(['product_id'=>$v['product_id'],'production_time'=>$v['production_time']])->setInc('peisong_num',$v['num']);
                        }
                        Db::commit();
                        return $this->success('操作成功');
                    }else{
                        return $this->error('订单状态异常');
                    }
                }else{
                    return $this->error('订单不存在');
                }
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('操作失败');
            }

        }else{
            return $this->error('非法请求');
        }
        return $this->success();
    }

    public function save_wuliu(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['order_id']) || empty($param['kuaidi']) || empty($param['kuaidino'])){
                return $this->error('缺少参数');
            }
            Db::startTrans();
            try{
                $Order = \app\common\model\Order::where('id',$param['order_id'])->find();
                if($Order){
                    if($Order->status == DictConstant::Order_Stock_up){
                        $Order->status = DictConstant::OrderAlreadyShipped;
                        $Order->express_name = $param['kuaidi'];
                        $Order->express_no = $param['kuaidino'];
                        $Order->save();
                        Orderitem::where('order_id',$param['order_id'])->update(['old_status'=>DictConstant::OrderAlreadyShipped]);
                        Db::commit();
                        //订阅快递鸟物流跟踪接口
                        $requestData = $this->SubscribeLogistics($param['order_id']);
                        $express = new \app\lib\express\Express();
                        $res = $express->orderTracesSubByJson($requestData);
                        if($res['Success']){
                            return $this->success('物流推送订阅成功');
                        }else{
                            return $this->success('物流推送订阅失败');
                        }

                    }else{
                        return $this->error('订单状态异常');
                    }
                }else{
                    return $this->error('该订单不存在');
                }
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('操作失败');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function order_track(Request $request){
        $param = $request->param();
        $this->assign('order_id',$param['order_id']);
        $Order = \app\common\model\Order::where('id',$param['order_id'])->field('express_name,express_no')->find();
        $Express = \app\admin\model\Express::where('code',$Order->express_name)->find();
        $expressinfo['name'] = $Express->name;
        $expressinfo['express_no'] = $Order->express_no;
        $ExpressTrace = ExpressTrace::where('express_no',$Order->express_no)->find();
        if($ExpressTrace){
            $traces = json_decode($ExpressTrace->traces,true);
            $state = $ExpressTrace->state;
        }else{
            $traces = '';
            $state = 0;
        }
        if(is_array($traces)){
            $traces = array_reverse($traces);
        }
        return $this->fetch('',[
            'expressinfo' => $expressinfo,
            'traces' => $traces,
            'status' => $state
        ]);
    }

    private function SubscribeLogistics($order_id){
        //查询订单信息
        $Order = \app\common\model\Order::where('id',$order_id)->field('express_name,express_no,address_id,member_id')->find();
        $data['OrderCode'] = $order_id;
        $data['ShipperCode'] = $Order->express_name;
        $data['LogisticCode'] = $Order->express_no;
        $Address = Address::where(['id'=>$Order->address_id,'memberId'=>$Order->member_id])->find();
        $data['ReceiverName'] = $Address->name;
        $data['ReceiverMobile'] = $Address->phone;
        $data['ReceiverProvinceName'] = $Address->province;
        $data['ReceiverCityName'] = $Address->city;
        $data['ReceiverExpAreaName'] = $Address->area;
        $data['ReceiverAddress'] = $Address->details;
        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['order_no']) && $param['order_no']){
            $where['order_no'] = ['like', '%'.$param['order_no'].'%'];
        }
        if(isset($param['account_number']) && $param['account_number']){
            $where['account_number'] = ['like', '%'.$param['account_number'].'%'];
        }
        if(isset($param['deliver_method']) && $param['deliver_method']){
            $where['deliver_method'] = $param['deliver_method'];
        }
        if(isset($param['status']) && $param['status']){
            $where['status'] = $param['status'];
        }
        if(isset($param['range_date']) && $param['range_date']){
//            $where['time'] = str_replace('+','',$param['time']);
//            $where['time'] = preg_replace('# #','',$where['time']);
//            $where['time'] = explode ('到',$where['time']);
//            $where['create_date'] = ['between',[$where['time'][0],$where['time'][1]]];
            $rangeDate = explode(' ~ ', $param['range_date']);
            $startTime = $rangeDate[0];
            $endTime = $rangeDate[1];
            $where['a.create_date'] = [['egt', $startTime], ['elt', $endTime], 'and'];
        }

        return $where;
    }

    private function show($template, $data = []) {

        return $this->view->fetch($template, $data);
    }
}
